package models

import (
	"time"

	"gorm.io/gorm"
)

// ChatMessage 聊天消息模型
type ChatMessage struct {
	gorm.Model
	ID          uint      `json:"id" gorm:"primaryKey"`
	RoomID      string    `json:"room_id" gorm:"size:100;not null;index"`
	UserID      uint      `json:"user_id" gorm:"not null;index"`
	UserName    string    `json:"user_name" gorm:"size:100;not null"`
	Content     string    `json:"content" gorm:"type:text;not null"`
	MessageType string    `json:"message_type" gorm:"size:20;default:'text'"`
	Timestamp   time.Time `json:"timestamp" gorm:"autoCreateTime"`
}

// ChatRoom 聊天房间模型
type ChatRoom struct {
	gorm.Model
	ID        uint   `json:"id" gorm:"primaryKey"`
	RoomID    string `json:"room_id" gorm:"size:100;uniqueIndex;not null"`
	RoomName  string `json:"room_name" gorm:"size:200"`
	RoomType  string `json:"room_type" gorm:"size:20;default:'private'"` // private, group
	CreatedBy uint   `json:"created_by" gorm:"not null"`
	IsActive  bool   `json:"is_active" gorm:"default:true"`
}

// OnlineUser 在线用户模型
type OnlineUser struct {
	gorm.Model
	ID       uint      `json:"id" gorm:"primaryKey"`
	UserID   uint      `json:"user_id" gorm:"not null;index"`
	SocketID string    `json:"socket_id" gorm:"size:100;not null;uniqueIndex"`
	UserName string    `json:"user_name" gorm:"size:100;not null"`
	IsOnline bool      `json:"is_online" gorm:"default:true"`
	LastSeen time.Time `json:"last_seen"`
}

// 消息类型常量
const (
	MessageTypeText  = "text"
	MessageTypeImage = "image"
	MessageTypeFile  = "file"
	MessageTypeVoice = "voice"
)

// 房间类型常量
const (
	RoomTypePrivate = "private"
	RoomTypeGroup   = "group"
)

// CreateChatMessage 创建聊天消息
func CreateChatMessage(message *ChatMessage) error {
	return GetDB().Create(message).Error
}

// GetChatMessages 获取聊天消息
func GetChatMessages(roomID string, limit, offset int) ([]ChatMessage, error) {
	var messages []ChatMessage
	err := GetDB().Where("room_id = ?", roomID).
		Order("timestamp DESC").
		Limit(limit).
		Offset(offset).
		Find(&messages).Error
	return messages, err
}

// CreateChatRoom 创建聊天房间
func CreateChatRoom(room *ChatRoom) error {
	return GetDB().Create(room).Error
}

// GetChatRoom 获取聊天房间
func GetChatRoom(roomID string) (*ChatRoom, error) {
	var room ChatRoom
	err := GetDB().Where("room_id = ? AND is_active = ?", roomID, true).First(&room).Error
	return &room, err
}

// AddOnlineUser 添加在线用户
func AddOnlineUser(user *OnlineUser) error {
	// 先删除该用户的其他连接
	GetDB().Where("user_id = ?", user.UserID).Delete(&OnlineUser{})
	return GetDB().Create(user).Error
}

// RemoveOnlineUser 移除在线用户
func RemoveOnlineUser(socketID string) error {
	return GetDB().Where("socket_id = ?", socketID).Delete(&OnlineUser{}).Error
}

// GetOnlineUsers 获取在线用户列表
func GetOnlineUsers() ([]OnlineUser, error) {
	var users []OnlineUser
	err := GetDB().Where("is_online = ?", true).Find(&users).Error
	return users, err
}

// GetOnlineUserBySocketID 根据SocketID获取在线用户
func GetOnlineUserBySocketID(socketID string) (*OnlineUser, error) {
	var user OnlineUser
	err := GetDB().Where("socket_id = ?", socketID).First(&user).Error
	return &user, err
}

// UpdateUserLastSeen 更新用户最后在线时间
func UpdateUserLastSeen(userID uint) error {
	return GetDB().Model(&OnlineUser{}).
		Where("user_id = ?", userID).
		Update("last_seen", time.Now()).Error
}

// GetChatMessagesCount 获取房间消息数量
func GetChatMessagesCount(roomID string) int64 {
	var count int64
	GetDB().Model(&ChatMessage{}).Where("room_id = ?", roomID).Count(&count)
	return count
}

// GetUserChatRooms 获取用户参与的聊天房间
func GetUserChatRooms(userID uint) ([]ChatRoom, error) {
	var rooms []ChatRoom
	err := GetDB().Where("created_by = ? AND is_active = ?", userID, true).Find(&rooms).Error
	return rooms, err
}
